/*
 * @Descripttion:
 * @version:
 * @Author: ChenXiang
 * @Date: 2021-03-22 16:18:10
 * @LastEditors: ChenXiang
 * @LastEditTime: 2021-10-29 15:01:19
 */

/**
 * 请求参数转字符串
 * @param {*} params对象
 * @returns a=1&b=2 字符串
 */
export default {
  /**
   *
   * @param url 网址
   * @param name 网址参数
   * @param value 网址值
   * @returns string
   * @example // UrlUpdateParams("/home?source=1","source1","23123")=> /home?source=1&source1=23123
   * @example // UrlUpdateParams("/home?source=1","source","23123") => /home?source=23123
   */



  UrlUpdateParams: function (url, name, value) {
    let r = url;
    if (r !== null && r !== "undefined" && r !== "") {
      value = encodeURIComponent(value);
      const reg: any = new RegExp("(^|)" + name + "=([^&]*)(|$)");
      const tmp = name + "=" + value;
      if (url.match(reg) !== null) {
        // eslint-disable-next-line no-eval
        r = url.replace(eval(reg), tmp);
      } else {
        if (url.match("[?]")) {
          r = url + "&" + tmp;
        } else {
          r = url + "?" + tmp;
        }
      }
    }
    return r;
  },
  // getDomain: function (url) {//有缺陷
  //   const re = /(\w+):\/\/([^\/:]+)(:\d*)?([^# ]*)/;
  //   return url.match(re)[2]
  // },
  objToString: (params: Object) => {
    if (params === null) {
      return params;
    }
    const arr = [];
    for (const i in params) {
      const str = i + "=" + params[i];
      arr.push(str);
    }
    return arr.join("&");
  },

  getAllUrlParams: (str: string) => {
    const q = {};
    str.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => (q[k] = decodeURI(v)));
    return q;
  },

  /**
   * 通过url地址返回一个面包屑
   * @param  url   url地址
   * @return Array 返回面包屑地址
   * @example
   * urlToCrumbs(/userinfo/2144/id)
   * return ['/userinfo','/useinfo/2144,'/userindo/2144/id']
   */

  urlToCrumbs: (url: string) => {
    const urllist = url.split("/").filter((i) => i);
    return urllist.map((urlItem, index) => {
      return `/${urllist.slice(0, index + 1).join("/")}`;
    });
  }
};
